//
// Created by 文道江 on 15/12/1.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "HybridMAudioAction.h"
#import "FZEasyFile.h"
#import "CocoaSecurity.h"

@interface HybridMAudioAction () <AVAudioRecorderDelegate>

@property(nonatomic, strong) AVAudioRecorder *audioRecorder;
//音频录音机
@property(nonatomic, strong) AVAudioPlayer *audioPlayer;
//音频播放器
@property(nonatomic, strong) NSTimer *timer;//录音声波监控（注意这里暂时不对播放进行监控）

@end

@implementation HybridMAudioAction

- (void)startRecord:(id)params {

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
    [audioSession setActive:YES error:nil];

    if (![self.audioRecorder isRecording]) {
        [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
        self.timer.fireDate = [NSDate distantPast];
    }
    [self callback:YES data:nil];
}

- (void)pauseRecord:(id)params {
    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder pause];
        self.timer.fireDate = [NSDate distantFuture];
    }
}

- (void)resumelRecord:(id)params {

}

- (void)cancelRecord:(id)params {

}

- (void)stopRecord:(id)params {
    [self.audioRecorder stop];
    self.timer.fireDate = [NSDate distantFuture];
    _audioRecorder = nil;
}

- (void)playAudio:(id)params {
    if (_audioPlayer) {
        if (_audioPlayer.isPlaying){
            [_audioPlayer stop];
        }
        _audioPlayer = nil;
    }
    if (params[@"url"] == nil){
        [self callback:NO data:@"param 'url' not found."];
        return;
    }
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
    [audioSession setActive:YES error:nil];

    NSURL *url = [NSURL fileURLWithPath:params[@"url"]];
    NSError *error;
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    _audioPlayer.numberOfLoops = 0;

    if (error) {
        NSLog(@"创建播放器过程中发生错误，错误信息：%@", error.localizedDescription);
        [self callback:NO data:error.localizedDescription];
    }else{
        if (![_audioPlayer prepareToPlay]){
            [self callback:NO data:@"预播放失败"];
        }else{
            [self callback:[_audioPlayer play] data:nil];
            //[NSTimer scheduledTimerWithTimeInterval:1 target:_audioPlayer selector:@selector(play) userInfo:nil repeats:NO];
        }
    }
}

- (void)stopAudio:(id)params{
    if (_audioPlayer) {
        if (_audioPlayer.isPlaying){
            [_audioPlayer stop];
        }
        _audioPlayer = nil;
    }
}

#pragma mark  -

/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
- (NSDictionary *)getAudioSetting {
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    //设置录音格式
    dicM[AVFormatIDKey] = @(kAudioFormatMPEG4AAC);
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    dicM[AVSampleRateKey] = @(8000);
    //设置通道,这里采用单声道
    dicM[AVNumberOfChannelsKey] = @(1);
    //每个采样点位数,分为8、16、24、32
    dicM[AVLinearPCMBitDepthKey] = @(8);
    //是否使用浮点数采样
    dicM[AVLinearPCMIsFloatKey] = @(YES);
    //....其他设置等
    return dicM;
}

/**
 *  取得录音文件保存路径
 *
 *  @return 录音文件路径
 */
- (NSURL *)getSavePath {

    if (![FZEasyFile isFileExists:@"audio/"]) {
        [FZEasyFile createFile:@"audio/" overwrite:NO];
    }

    NSString *urlStr = [FZEasyFile fullFileName:@"audio"];
    NSString *fileName = [@"record_" stringByAppendingString:[CocoaSecurity md5:[NSString stringWithFormat:@"%lf", [NSDate timeIntervalSinceReferenceDate]]].hexLower];
    urlStr = [urlStr stringByAppendingFormat:@"/%@.caf", fileName];
    NSLog(@"file path:%@", urlStr);
    NSURL *url = [NSURL fileURLWithPath:urlStr];
    return url;
}


/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
- (AVAudioRecorder *)audioRecorder {
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url = [self getSavePath];
        //创建录音格式设置
        NSDictionary *setting = [self getAudioSetting];
        //创建录音机
        NSError *error = nil;
        _audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate = self;
        _audioRecorder.meteringEnabled = YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@", error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

/**
 *  录音声波监控定制器
 *
 *  @return 定时器
 */
- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(audioPowerChange) userInfo:nil repeats:YES];
    }
    return _timer;
}

/**
 *  录音声波状态设置
 */
- (void)audioPowerChange {
    [self.audioRecorder updateMeters];//更新测量值
    CGFloat power = [self.audioRecorder averagePowerForChannel:0];//取得第一个通道的音频，注意音频强度范围时-160到0
    CGFloat progress =  ((100.0F / 160.0F) * (power + 160.0F));
    NSLog(@"录音声波状态设置 %f", progress);
    [self dispatchEvent:@"audioRecorderPowerChange" data:@{
            @"progress" : @(progress)
    }];
}

#pragma mark - 录音机代理方法

/**
 *  录音完成，录音完成后播放录音
 *
 *  @param recorder 录音机对象
 *  @param flag     是否成功
 */
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    /*if (![self.audioPlayer isPlaying]) {
        [self.audioPlayer play];
    }*/
    NSLog(@"录音完成!");


    [self callback:YES data:@{
            @"file" : recorder.url.relativePath,
            @"url" : recorder.url.absoluteString,
            @"currentTime": @(recorder.currentTime)
    }];
}

@end